package common;

import static utils.Tools.listOf;

/**
 * 二分法查找
 */
public class SearchBinary {

    public static void main(String[] args) {
        println(new int[]{0}, -1);
        println(new int[]{1, 2, 3}, 2);
    }

    public static void println(int nums[], int target) {
        System.out.println(listOf(nums) + ", " + target + ", " + binarySearch(nums, target));
    }

    public static int binarySearch(int nums[], int target) {
        int left = 0, right = nums.length - 1;

        while (left <= right) {
            int mid = left + ((right - left) >> 1);
            if (nums[mid] == target) {
                return mid;
            } else if (target > nums[mid]) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }
}
